package com.briup.sxau.conf;

import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket webApiConfig(){

        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("webAPI")
                .apiInfo(genInfo())
                .select()
                .paths(Predicates.not(PathSelectors.regex("/error.*")))
                .build()
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
    }

    private  List<SecurityContext> securityContexts(){
        List<SecurityContext> list = new ArrayList();
        list.add(SecurityContext
                .builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex("^(?!auth).*$"))
                .build()
        );

        return list;
    }

    private List<SecurityReference> defaultAuth(){
        AuthorizationScope as = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] arr = new AuthorizationScope[1];
        arr[0]=as;
        ArrayList<SecurityReference> list = new ArrayList<>();
        list.add(new SecurityReference("Authorization",arr));
        return list;
    }

    private List<ApiKey> securitySchemes(){
        ArrayList<ApiKey> list = new ArrayList<>();
        list.add(new ApiKey("Authorization","token","header"));
        return list;
    }

    public ApiInfo genInfo(){
        return new ApiInfoBuilder()
                .title("山西农业大学联系文档")
                .description("练习Springboot整合SpringDataJpa以及SpringWeb")
                .version("1.0")
                .contact(new Contact("stt","www.sxau.com","2719612830@qq.com"))
                .build();

    }
}
